package com.sxu.demo.reentrantlock;

import java.util.concurrent.locks.ReentrantLock;

import static java.lang.Thread.sleep;

// 可打断
public class Test2 {
    private static ReentrantLock reentrantLock = new ReentrantLock();
    public static void main(String[] args) throws InterruptedException {
        Thread t1 = new Thread(()->{
            try {
                // 没有竞争 —— 获取锁
                // 有竞争 —— 进入阻塞队列，可以被其他线程打断等待
                System.out.println(Thread.currentThread().getName() + "尝试获取锁");
                reentrantLock.lockInterruptibly();
            } catch (InterruptedException e) {
                e.printStackTrace();
                System.out.println(Thread.currentThread().getName() + "没有获取锁");
                return;
            }
            try{
                System.out.println(Thread.currentThread().getName() + "获取锁");
            } finally {
                reentrantLock.unlock();
            }

        },"t1");
        // 主线程先加锁，t1就会进入阻塞
        reentrantLock.lock();
        t1.start();
        sleep(1);
        System.out.println("打断t1");
        t1.interrupt();
    }
}
